import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-07-15
 * Time: 20:57
 */
//https://leetcode.cn/problems/binary-tree-level-order-traversal/
    //给你二叉树的根节点 root ，返回其节点值的 层序遍历 。 （即逐层地，从左到右访问所有节点）
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Test {
    public static List<List<Integer>> levelOrder(TreeNode root) {
        ArrayList<ArrayList> lists=new ArrayList();
        if(root==null){
            return (List)lists;
        }
        LinkedList<TreeNode> queue=new LinkedList();
        queue.offer(root);
        TreeNode p=null;
        int j=0;
        int n=1;
        while(!queue.isEmpty()){
            ArrayList list=new ArrayList();
            for(int i=0;i<n;i++){
                p=queue.poll();
                if(p==null){
                    continue;
                }
                list.add(p.val);
                queue.offer(p.left);
                queue.offer(p.right);
                j=j+2;
            }
            n=j;
            j=0;
            lists.add(list);
        }
        lists.remove(lists.size()-1);
        return (List)lists;
    }
    public static void main(String[] args) {
        TreeNode A1=new TreeNode(1);
        TreeNode A2=new TreeNode(2);
        TreeNode A3=new TreeNode(3);
        TreeNode A4=new TreeNode(4);
        TreeNode A5=new TreeNode(5);
        TreeNode A6=new TreeNode(6);
        TreeNode A7=new TreeNode(7);
        A1.left=A2;A1.right=A3;
        A2.left=A4;A2.right=A5;
        A3.left=A6;A3.right=A7;
        ArrayList list=(ArrayList) levelOrder(A1);
        System.out.println(list.toString());
    }
}
